#pragma once

#include <sys/select.h>
#include <unistd.h>
#include <cerrno>
#include <ctime>
#include <cstring>
#include <string>
#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define DEL -1

using namespace std;

class Sock
{
public:
    static const int gbacklog = 20;

    static int Socket()
    {
        int listenSock = socket(AF_INET, SOCK_STREAM, 0);
        if (listenSock < 1)
        {
            exit(1);
        }
        int opt = 1;
        setsockopt(listenSock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        return listenSock;
    }
    static void Bind(int socket, uint16_t port)
    {
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if (bind(socket, (const struct sockaddr *)&local, sizeof(local)) < 0)
        {
            exit(2);
        }
    }

    static void Listen(int socket)
    {
        if (listen(socket, gbacklog) < 0)
        {
            exit(3);
        }
    }
    static int Accept(int socket, std::string &ip, uint16_t &port)
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);

        int clientSock = accept(socket, (struct sockaddr *)&client, &len);
        if (clientSock < 0)
        {
            return -1;
        }

        ip = inet_ntoa(client.sin_addr);
        port = ntohs(client.sin_port);
        return clientSock;
    }
};
